import React, { useState, useEffect } from 'react';
import { Layout, Menu, Button, theme, Avatar, Dropdown } from 'antd';
import './MainLayout.css';
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  UserOutlined,
  DashboardOutlined,
  SettingOutlined,
  LogoutOutlined,
  ProjectOutlined,
  CalendarOutlined,
  FieldTimeOutlined,
  FileOutlined,
  TeamOutlined,
  AppstoreOutlined,
  ScheduleOutlined,
  CheckCircleOutlined,
  BarsOutlined,
  UserAddOutlined,
  ClockCircleOutlined,
  FileDoneOutlined,
  FileTextOutlined,
  FileSearchOutlined,
  FileAddOutlined,
  ApartmentOutlined,
} from '@ant-design/icons';
import { useNavigate, Outlet } from 'react-router-dom';

const { Header, Sider, Content } = Layout;

// 定义菜单类型
type MenuKey = 'home' | 'project-plan' | 'project-activity' | 'project-progress' | 'document-management' | 'member-management';

interface MenuItem {
  key: string;
  icon: React.ReactNode;
  label: string;
}

interface SubMenuConfig {
  'home': MenuItem[];
  'project-plan': MenuItem[];
  'project-activity': MenuItem[];
  'project-progress': MenuItem[];
  'document-management': MenuItem[];
  'member-management': MenuItem[];
}

const MainLayout: React.FC = () => {
  const [collapsed, setCollapsed] = useState(false);
  const [selectedMenu, setSelectedMenu] = useState<MenuKey>('project-plan');
  const navigate = useNavigate();
  const {
    token: { colorBgContainer },
  } = theme.useToken();

  // 一级导航菜单
  const mainMenuItems: {key: MenuKey; icon: React.ReactNode; label: string}[] = [
    {
      key: 'home',
      icon: <DashboardOutlined />,
      label: '首页',
    },
    {
      key: 'project-plan',
      icon: <ProjectOutlined />,
      label: '项目计划管理',
    },
    {
      key: 'project-activity',
      icon: <CalendarOutlined />,
      label: '项目活动管理',
    },
    {
      key: 'project-progress',
      icon: <FieldTimeOutlined />,
      label: '项目进度管理',
    },
    {
      key: 'document-management',
      icon: <FileOutlined />,
      label: '文档文件管理',
    },
    {
      key: 'member-management',
      icon: <TeamOutlined />,
      label: '成员单位管理',
    },
  ];

  // 二级菜单配置
  const subMenuConfig: SubMenuConfig = {
    'home': [],
    'project-plan': [
      { key: 'plan-create', icon: <AppstoreOutlined />, label: '计划创建' },
      { key: 'plan-review', icon: <ScheduleOutlined />, label: '计划审核' },
      { key: 'plan-approval', icon: <CheckCircleOutlined />, label: '计划审批' },
      { key: 'plan-adjustment', icon: <BarsOutlined />, label: '计划调整' },
    ],
    'project-activity': [
      { key: 'activity-create', icon: <CalendarOutlined />, label: '活动创建' },
      { key: 'activity-assign', icon: <UserAddOutlined />, label: '活动分配' },
      { key: 'activity-tracking', icon: <ClockCircleOutlined />, label: '活动跟踪' },
      { key: 'activity-report', icon: <FileDoneOutlined />, label: '活动报告' },
    ],
    'project-progress': [
      { key: 'progress-overview', icon: <DashboardOutlined />, label: '进度概览' },
      { key: 'progress-update', icon: <FieldTimeOutlined />, label: '进度更新' },
      { key: 'progress-report', icon: <FileTextOutlined />, label: '进度报告' },
      { key: 'progress-analysis', icon: <FileSearchOutlined />, label: '进度分析' },
    ],
    'document-management': [
      { key: 'document-upload', icon: <FileAddOutlined />, label: '文档上传' },
      { key: 'document-review', icon: <FileSearchOutlined />, label: '文档审阅' },
      { key: 'document-approval', icon: <FileDoneOutlined />, label: '文档审批' },
      { key: 'document-archive', icon: <FileOutlined />, label: '文档归档' },
    ],
    'member-management': [
      { key: 'member-register', icon: <UserAddOutlined />, label: '成员注册' },
      { key: 'member-role', icon: <ApartmentOutlined />, label: '角色分配' },
      { key: 'member-permission', icon: <SettingOutlined />, label: '权限管理' },
      { key: 'member-organization', icon: <TeamOutlined />, label: '组织架构' },
    ],
  };

  const userMenuItems = [
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: '个人信息',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
    },
  ];

  const handleMainMenuClick = (key: string) => {
    console.log('Menu clicked:', key); // 添加日志以便调试
    setSelectedMenu(key as MenuKey);
    if (key === 'home') {
      navigate('/home');
    }
  };

  // 监听 selectedMenu 变化，确保当它是 'home' 时隐藏侧边栏
  useEffect(() => {
    console.log('selectedMenu changed:', selectedMenu);
  }, [selectedMenu]);

  const handleSubMenuClick = (key: string) => {
    // 导航到相应的页面
    navigate(`/${key}`);
  };

  const handleUserMenuClick = ({ key }: { key: string }) => {
    switch (key) {
      case 'profile':
        navigate('/profile');
        break;
      case 'logout':
        // TODO: 实现登出逻辑
        navigate('/login');
        break;
      default:
        break;
    }
  };

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Header className="custom-header" style={{ 
        background: colorBgContainer, 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center',
        padding: '0 16px',
        height: '64px',
        boxShadow: '0 1px 4px rgba(0,21,41,.08)'
      }}>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <div 
            style={{ 
              fontSize: '20px', 
              fontWeight: 'bold', 
              marginRight: '24px',
              background: 'linear-gradient(to right, #1890ff, #52c41a)',
              WebkitBackgroundClip: 'text',
              WebkitTextFillColor: 'transparent',
              textShadow: '0 1px 2px rgba(0,0,0,0.1)',
              letterSpacing: '1px'
            }}
          >
            XX平台装备流程管理系统
          </div>
          <Menu
            mode="horizontal"
            selectedKeys={[selectedMenu]}
            onClick={({ key }) => handleMainMenuClick(key as string)}
            style={{ border: 'none', flex: 1 }}
            items={mainMenuItems}
          />
        </div>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Dropdown
            menu={{
              items: userMenuItems,
              onClick: handleUserMenuClick,
            }}
            placement="bottomRight"
          >
            <div style={{ cursor: 'pointer', display: 'flex', alignItems: 'center' }}>
              <Avatar icon={<UserOutlined />} />
              <span style={{ marginLeft: 8 }}>管理员</span>
            </div>
          </Dropdown>
        </div>
      </Header>
      <Layout>
        {selectedMenu !== 'home' ? (
          <Sider 
            width={200} 
            theme="light" 
            style={{ 
              background: colorBgContainer,
              boxShadow: '2px 0 8px 0 rgba(29,35,41,.05)',
              margin: '24px 0 24px 24px',
              borderRadius: '4px',
              height: 'calc(100vh - 112px)'
            }}
            collapsed={collapsed}
            collapsible
            trigger={null}
          >
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
            style={{ margin: '16px', width: '100%' }}
          />
          <Menu
            mode="inline"
            style={{ height: '100%', borderRight: 0 }}
            inlineCollapsed={collapsed}
            items={subMenuConfig[selectedMenu]}
            onClick={({ key }) => handleSubMenuClick(key as string)}
          />
        </Sider>
        ) : null}
        <Content
          style={{
            margin: '24px',
            padding: 24,
            background: colorBgContainer,
            borderRadius: '4px',
            minHeight: 'calc(100vh - 112px)',
          }}
          className="custom-content"
        >
          {/* 添加调试信息 */}
          <div style={{ marginBottom: '10px', color: '#999' }}>
            当前选中的菜单: {selectedMenu}
          </div>
          <Outlet />
        </Content>
      </Layout>
    </Layout>
  );
};

export default MainLayout;